import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
      GeneratedPluginRegistrant.register(with: self)
      // native view
      weak var registrar = self.registrar(forPlugin: "plugins.flutter/flnative_plugin")
      let factory = FLNativeViewFactory(messenger: registrar!.messenger())
      registrar!.register(
        factory,
        withId: "plugins.flutter/flnative_view")
      // native method
      let controller: FlutterViewController = window?.rootViewController as! FlutterViewController
      let batteryChannerl = FlutterMethodChannel.init(name: "plugins.methods/battery", binaryMessenger: controller.binaryMessenger)
      batteryChannerl.setMethodCallHandler({
          [weak self] (call: FlutterMethodCall, result: FlutterResult) -> Void in
          guard call.method == "getBatteryLevel" else {
              result(FlutterMethodNotImplemented)
              return
          }
          self?.receiveBatteryLevel(result: result)
      })
      
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
    private func receiveBatteryLevel(result: FlutterResult) {
        let device = UIDevice.current
        device.isBatteryMonitoringEnabled = true
        print(device.batteryState)
        print(device.batteryLevel)
        if device.batteryState == UIDevice.BatteryState.unknown {
            result(FlutterError(code: "UNAVAILABLE", message: "Battery info unavailable", details: nil))
        } else {
            result(Int(device.batteryLevel * 100))
        }
    }
}
